package org.wdcode.web.mina.service;

import java.net.InetSocketAddress;
import java.util.List;

import org.apache.mina.core.service.IoConnector;
import org.wdcode.common.util.CommonUtil;
import org.wdcode.web.mina.filter.MinaIoFilter;
import org.wdcode.web.mina.need.MinaConnectorNeed;

/**
 * mina IO连接器 实现类
 * @author WD
 * @since JDK6
 * @version 1.0 2010-08-05
 */
final class MinaIoConnectorImpl implements MinaIoConnector {
	// Mina包装
	private MinaConnectorNeed	need;
	// IO连接器
	private IoConnector			ioConnector;

	/**
	 * 构造方法
	 * @param need Mina包装
	 */
	public MinaIoConnectorImpl(MinaConnectorNeed need) {
		this.need = need;
		this.ioConnector = need.getIoConnector();
	}

	/**
	 * 初始化方法
	 */
	public final void init() {
		// 获得过滤器列表
		List<MinaIoFilter> list = need.getIoFilters();
		// 判断过滤器不为空
		if (!CommonUtil.isEmpty(list)) {
			// Mina 过滤器
			MinaIoFilter ioFilter = null;
			// 循环过滤器列表
			for (int i = 0; i < list.size(); i++) {
				// 获得过滤器
				ioFilter = list.get(i);
				// 添加过滤器
				ioConnector.getFilterChain().addLast(ioFilter.getName(), ioFilter.getIoFilter());
			}
		}
		// 设置超时时间
		ioConnector.setConnectTimeoutMillis(need.getConnectTimeoutMillis());
		// 设置IO处理器
		ioConnector.setHandler(need.getIoHandler());
	}

	/**
	 * 关闭资源
	 */
	public final void close() {
		// 清除过滤器
		ioConnector.getFilterChain().clear();
		// 清除处理器
		ioConnector.setHandler(null);
		// 清除地址
		ioConnector.setDefaultRemoteAddress(null);
		// 销毁资源
		ioConnector.dispose();
	}

	/**
	 * 连接服务器
	 */
	public final void connect() {
		ioConnector.connect(new InetSocketAddress(need.getHost(), need.getPort())).awaitUninterruptibly();
	}

	/**
	 * 获得Mina包装
	 * @return Mina包装
	 */
	public final MinaConnectorNeed getNeed() {
		return need;
	}

	/**
	 * 设置Mina包装
	 * @param need Mina包装
	 */
	public final void setNeed(MinaConnectorNeed need) {
		this.need = need;
	}

	/**
	 * 获得IO连接器
	 * @return IO连接器
	 */
	public final IoConnector getIoConnector() {
		return ioConnector;
	}

	/**
	 * 设置
	 * @param ioConnector IO连接器
	 */
	public final void setIoConnector(IoConnector ioConnector) {
		this.ioConnector = ioConnector;
	}
}
